<template>
  <div>
    <Col :lg="24" :md="16">
      <Card class="warp-card" dis-hover>
        <Row justify="space-between" type="flex">
          <Col>
            <Input
              placeholder="节点元素名称"
              style="width: 200px;"
              v-model="searchForm.name"
            />
            <Button
              @click="searchData" icon="md-search"
              style="margin-left: 20px;"
              type="primary"
              v-privilege="'search-nodeConfig'"
            >查询
            </Button>
            <Button
              @click="clearSearch"
              style="margin-left: 20px;"
              icon="md-refresh"
              type="default"
              v-privilege="'search-nodeConfig'"
            >重置
            </Button>
          </Col>
          <Col>
            <Button
              @click="isShowAddModal=true"
              icon="md-add"
              type="primary"
              v-privilege="'add-nodeConfig'"
            >新建
            </Button>
          </Col>
        </Row>
        <!-- Form 搜索按钮区 end -->
        <Row style="padding-top:10px; ">
          <Col :lg="24" :md="24">
            <Table :columns="columns" :data="data" :loading="isShowTablesLoading" ref="tablesMain"></Table>
          </Col>
        </Row>
        <Row class="page" justify="end" style="position: relative;margin-top: 10px;" type="flex">
          <Page
            :current="searchForm.pageNum"
            :page-size="searchForm.pageSize"
            :total="totalPage"
            @on-change="changePage"
            show-total
            show-elevator
          ></Page>
        </Row>
      </Card>
      <!-- Card 内容区 end -->
      <Modal
        :loading="isShowUpdateLoading"
        :closable="false"
        title="编辑配置节点名称"
        width="740"
        v-model="isShowEditModal"
      >
        <Form :label-width="100" :model="updateItem" :rules="updateValidate" ref="updateRef">
          <FormItem label="节点元素名称" prop="name">
            <Input :maxlength="50" placeholder="请输入节点名称(必填)" v-model="updateItem.name"></Input>
          </FormItem>
          <FormItem label="节点元素类型" prop="type">
            <RadioGroup v-model="updateItem.type">
              <Radio v-for="item in configTypeList" :key="item.code" :label="item.code">{{item.message}}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="异常描述" prop="isThrowDesc">
            <RadioGroup v-model="updateItem.isThrowDesc">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="是否有照片" prop="hasImage">
            <RadioGroup v-model="updateItem.hasImage">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="接口获取照片" prop="interfaceImage">
            <RadioGroup v-model="updateItem.interfaceImage">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
           <FormItem label="单位" prop="unit">
            <Input :maxlength="50" placeholder="请输入单位" v-model="updateItem.unit" style="width:35%"></Input>
          </FormItem>
          <FormItem label="是否固定" prop="fixed">
            <RadioGroup v-model="updateItem.fixed" @on-change="changeFixedStatus">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="所属节点" v-if="showRelateNode">
            <Select v-model="updateItem.taskNodeId" style="width:150px">
              <Option v-for="item in taskNodeList" :value="item.id" :key="item.id">{{item.nodeName}}</Option>
            </Select>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button
            @click="cancelUpdateData"
          >取消
          </Button>
          <Button
            type="primary"
            @click="validateAndupdateTaskNodeConfig"
          >保存
          </Button>
        </div>
      </Modal>
      <Modal
        :loading="isShowSaveLoading"
        title="新建自定义节点元素"
        :closable="false"
        width="740"
        v-model="isShowAddModal"
      >
        <Form :label-width="100" :model="saveItem" :rules="saveValidate" ref="saveRef">
          <FormItem label="节点元素名称" prop="name">
            <Input :maxlength="50" placeholder="请输入节点元素名称(必填)" v-model="saveItem.name"></Input>
          </FormItem>
          <FormItem label="节点元素类型" prop="type">
            <RadioGroup v-model="saveItem.type">
              <Radio v-for="item in configTypeList" :key="item.code" :label="item.code">{{item.message}}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="异常描述" prop="isThrowDesc">
            <RadioGroup v-model="saveItem.isThrowDesc">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="是否有照片" prop="hasImage">
            <RadioGroup v-model="saveItem.hasImage">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="接口获取照片" prop="interfaceImage">
            <RadioGroup v-model="saveItem.interfaceImage">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="单位" prop="unit">
            <Input :maxlength="50" placeholder="请输入单位" v-model="saveItem.unit" style="width:35%"></Input>
          </FormItem>
          <FormItem label="是否固定" prop="fixed">
            <RadioGroup v-model="saveItem.fixed" @on-change="changeFixedStatus">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="所属节点" v-if="showRelateNode">
            <Select v-model="saveItem.taskNodeId" style="width:150px">
              <Option v-for="item in taskNodeList" :value="item.id" :key="item.id">{{item.nodeName}}</Option>
            </Select>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button
            @click="cancelSaveData"
          >取消
          </Button>
          <Button
            type="primary"
            @click="validateAndAddTaskNode"
          >保存
          </Button>
        </div>
      </Modal>
    </Col>
  </div>
</template>

<script>
import {taskNodeConfigApi} from '@/api/task-node-config';
import {taskNodeApi} from '@/api/task-node';

export default {
  name: 'TaskNodeConfigManage',
  components: {},
  props: {},
  data() {
    return {
      isShowPage: true,
      searchValue: '',
      isShowEditModal: false,
      isShowAddModal: false,
      // table是否Loading
      isShowTablesLoading: true,
      isShowSaveLoading: true,
      isShowUpdateLoading: true,
      configTypeList:[],
      totalPage: 0,
      showRelateNode: false,
      taskNodeList: [],
      // 更新的数据
      updateItem: {
        id: "",
        name: '',
        type: '',
        isThrowDesc: "",
        hasImage: "",
        interfaceImage: "",
        fixed: "",
        disabled: false,
        isOther:"",
        unit:"",
        taskNodeId: null
      },
      // 添加保存的数据
      saveItem: {
        name: '',
        type: 1,
        isThrowDesc: "0",
        hasImage: "0",
        interfaceImage: "0",
        fixed: "0",
        isOther:"0",
        unit:"",
        taskNodeId: null
      },
      saveItemInt: {},
      // table表头
      columns: [
        // {
        //   title: '序号',
        //   width: 60,
        //   type: "index"
        // },
        {
          title: '节点元素名称',
          key: 'name'
        },
        {
          title: '节点元素类型',
          key: 'typeName'
        },
        {
          title: '是否异常描述',
          key: 'isThrowDescName'
        },
        {
          title: '是否照片',
          key: 'hasImageName'
        },
        {
          title: '接口获取照片',
          key: 'interfaceImageName'
        },
        {
          title: '是否固定',
          key: 'fixedDesc'
        },
        {
          title: '是否其他',
          key: 'isOtherDesc'
        },
        {
          title: '所属节点',
          key: 'taskNodeName'
        },
        {
          title: '创建人',
          key: 'createByName',
          width: 120
        },
        {
          key: 'createTime',
          width: 160,
          title: '创建时间',
          align: 'left'
        },
        {
          title: '更新人',
          key: 'updateByName',
          width: 120
        },
        {
          key: 'updateTime',
          width: 160,
          title: '更新时间',
          align: 'left'
        },
        {
          title: '操作',
          key: 'action',
          width: 100,
          align: 'center',
          className: 'action-hide',
          render: (h, params) => {
            return this.$tableAction(h, [
              {
                title: '编辑',
                directives: [
                  {
                    name: 'privilege',
                    value: 'update-nodeConfig'
                  }
                ],
                action: () => {
                  this.updateItem = {
                    id: params.row.id,
                    name: params.row.name,
                    type: params.row.type,
                    isThrowDesc: params.row.isThrowDesc + "",
                    hasImage: params.row.hasImage + "",
                    interfaceImage: params.row.interfaceImage + "",
                    fixed: params.row.fixed + "",
                    isOther: params.row.isOther + "",
                    taskNodeId: params.row.taskNodeId,
                    unit:params.row.unit,
                    disabled: params.row.fixed == 1 ? true : false
                  }
                  this.showRelateNode = params.row.fixed == 1;
                  this.isShowEditModal = true
                }
              },
              {
                title: '删除',
                directives: [
                  {
                    name: 'privilege',
                    value: 'delete-nodeConfig'
                  }
                ],
                action: () => {
                  this.$Modal.confirm({
                    title: '友情提醒',
                    content: '确定要删除吗？',
                    onOk: () => {
                      if (params.row.fixed === 1) {
                        this.$Message.error("固定节点元素不允许删除");
                        return;
                      }
                      this.deleteTaskNodeConfigById(params.row.id);
                    }
                  });
                }
              }
            ]);
          }
        }
      ],
      // table数据
      data: [],
      updateValidate: {
        name: [
          {required: true, message: '请输入节点配置名称', trigger: 'blur'}
        ]
      },
      saveValidate: {
        name: [
          {required: true, message: '请输入节点配置名称', trigger: 'blur'}
        ]
      },
      searchForm: {
        name: '',
        pageNum: 1,
        pageSize: 10,
        searchCount: true,
        sort: false
      },
      searchFormInt: {},
      isShowdeleteLoading: false
    };
  },
  computed: {},
  watch: {

  },
  filters: {},
  created() {
  },
  mounted() {
    Object.assign(this.searchFormInt, this.searchForm);
    Object.assign(this.saveItemInt, this.saveItem);
    this.getTaskNodeConfigListPage();
    this.initConfigType();
    this.initTaskNodeList();
  },
  beforeCreate() {
  },
  beforeMount() {
  },
  beforeUpdate() {
  },
  updated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  activated() {
  },
  methods: {
    // 分页查询任务节点
    async getTaskNodeConfigListPage() {
      try {
        this.isShowTablesLoading = true;
        this.isShowPage = true;
        let result = await taskNodeConfigApi.getTaskNodeConfigByPage(this.searchForm);
        this.isShowTablesLoading = false;
        let datas = result.data;
        this.data = datas.list;
        this.totalPage = datas.total;
      } catch (e) {
        this.isShowTablesLoading = false;
        console.error(e);
      }
    },
    // 页码改变
    changePage(pageNum) {
      this.searchForm.pageNum = pageNum;
      this.getTaskNodeConfigListPage();
    },
    // 改变每页显示数据条数
    changePageSize(pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.getTaskNodeConfigListPage();
    },
     //初始化部门
    async initConfigType(){
      let result = await taskNodeConfigApi.getConfigTypeList();
      this.configTypeList = result.data;
    },
    async initTaskNodeList() {
      let result = await taskNodeApi.getTaskNodeList();
      this.taskNodeList = result.data;
    },
    // 检验参数后 更新节点
    validateAndupdateTaskNodeConfig() {
      this.$refs['updateRef'].validate(valid => {
        this.isShowUpdateLoading = true;
        if (valid) {
          this.updateTaskNodeConfig();
        } else {
          this.isShowUpdateLoading = false;
          this.$nextTick(() => {
            this.isShowUpdateLoading = true;
          });
        }
      });
    },
    // 更新任务节点
    async updateTaskNodeConfig() {
      try {
        let result = await taskNodeConfigApi.updateTaskNodeConfig(this.updateItem);
        this.$Message.success('修改成功');
        this.$emit('updateSuccess');
        await this.getTaskNodeConfigListPage();
        this.cancelUpdateData();
      } catch (e) {
        this.isShowUpdateLoading = false;
        this.$nextTick(() => {
          this.isShowUpdateLoading = true;
        });
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowUpdateLoading = false;
      }
    },
    // 清除编辑模态框数据
    cancelUpdateData() {
      this.updateItem = {};
      // 清空form规则检查
      this.$refs['updateRef'].resetFields();
      this.isShowEditModal = false;
      this.showRelateNode = false;
    },
    // 搜索
    searchData() {
      this.pageNum = 1;
      this.getTaskNodeConfigListPage();
    },
    // 重置
    clearSearch() {
      Object.assign(this.searchForm, this.searchFormInt);
      this.getTaskNodeConfigListPage();
    },
    validateAndAddTaskNode() {
      try {
        this.$refs['saveRef'].validate(valid => {
          this.isShowSaveLoading = true;
          if (valid) {
            this.addTaskNode();
          } else {
            this.isShowSaveLoading = false;
            this.$nextTick(() => {
              this.isShowSaveLoading = true;
            });
          }
        });
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      }
    },
    // 新增节点 - 异步
    async addTaskNode() {
      try {
        let result = await taskNodeConfigApi.addTaskNodeConfig(this.saveItem);
        this.$Message.success('添加成功');
        this.$emit('addSuccess');
        this.isShowSaveLoading = true;
        await this.getTaskNodeConfigListPage();
        this.cancelSaveData();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowSaveLoading = false;
      }
    },
    // 清除添加模态框数据
    cancelSaveData() {
      Object.assign(this.saveItem, this.saveItemInt);
      // 清空form规则检查
      this.$refs['saveRef'].resetFields();
      this.isShowAddModal = false;
      this.showRelateNode = false;
    },
    // 根据ID删除节点
    async deleteTaskNodeConfigById(id) {
      try {
        this.isShowdeleteLoading = true;
        let result = await taskNodeConfigApi.deleteTaskNodeConfig(id);
        this.isShowdeleteLoading = false;
        this.$Message.success('删除成功');
        await this.getTaskNodeConfigListPage();
        this.cancelSaveData();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowdeleteLoading = false;
      }
    },
    changeFixedStatus(val) {
      if (val == 1)
        this.showRelateNode = true;
      else
        this.showRelateNode = false;
    }
  }
};
</script>
<style lang="less" scoped>
.text {
  position: absolute;
  right: 10px;
  bottom: -5px;
}
</style>
